

/**
 * 配置
 */
use actix_web::{post, web, Error, HttpResponse};
use crate::action::setting_action;
use crate::model::setting_model::*;
use crate::models::{self};
use super::DbPool;


/**
 * 按Key查询
 */
#[post("/api/settings/query")]
async fn settings_query(
    pool: web::Data<DbPool>,
    form: web::Json<SettingDTO>,
) -> Result<HttpResponse, Error> {
    if form.id.is_none() {
        let sys_result: models::SysResult<SettingDTO> = models::SysResult {
            success: true,
            error_code: "".to_string(),
            error_message: "id不能为空".to_string(),
            data: None,
        };
        return Ok(HttpResponse::Ok().json(sys_result));
    }

    let setting = web::block(move || {
        let conn = pool.get()?;
        setting_action::find_by_id(form.id.as_ref().unwrap(), &conn)
    })
    .await?
    .map_err(actix_web::error::ErrorInternalServerError)?;
    
    Ok(HttpResponse::Ok().json(models::SysResult {
        success: true,
        error_code: "".to_string(),
        error_message: "".to_string(),
        data: Some(setting),
    }))
}

/**
 * 新增
 */
#[post("/api/settings/update")]
async fn settings_update(
    pool: web::Data<DbPool>,
    form: web::Json<SettingDTO>,
) -> Result<HttpResponse, Error> {
    if form.id.is_none() || form.value.is_none() {
        let sys_result: models::SysResult<SettingDTO> = models::SysResult {
            success: true,
            error_code: "".to_string(),
            error_message: "id或value不能为空".to_string(),
            data: None,
        };
        return Ok(HttpResponse::Ok().json(sys_result));
    }

    let setting = web::block(move || {
        let conn = pool.get()?;
        setting_action::upsert(Setting { 
            id: form.id.as_ref().unwrap().to_string(), 
            value: form.value.as_ref().unwrap().to_string()
        }, &conn)
    })
    .await?
    .map_err(actix_web::error::ErrorInternalServerError)?;

    let sys_result: models::SysResult<SettingDTO> = models::SysResult {
        success: true,
        error_code: "".to_string(),
        error_message: "".to_string(),
        data: Some(SettingDTO {
            id: Some(setting.id),
            value: Some(setting.value)
        }),
    };
    Ok(HttpResponse::Ok().json(sys_result))
}
